<?php

namespace App\Http\Models;

use App\Observers\BosCleanObserver;
use App\Services\Utils\Bosable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\UploadedFile;

/**
 * @method self filterVideoTypeId(int $video_type_id)
 * @method self filterName(string $name)
 */
class Video extends Model
{
    use Bosable;

    public $bos_columns = ['preview_img', 'url'];  //  要删除bos的字段

    protected $guarded = [''];

    protected $table = 'videos';

    protected $img_bos_key_prefix = 'videos/img/';

    protected $url_bos_key_prefix = 'videos/url/';

    /**
     * @param Builder $query
     * @param $video_type_id
     * @return Builder
     */
    public function scopeFilterVideoTypeId(Builder $query, $video_type_id)
    {
        if (!$video_type_id) return $query;

        return $query->where( 'video_type_id' , $video_type_id );
    }

    /**
     * @param Builder $query
     * @param $name
     * @return Builder
     */
    public function scopeFilterName(Builder $query, $name)
    {
        if (!$name) return $query;

        return $query->where('name', 'like', '%'.$name.'%');
    }

    /**
     * @return mixed|null
     */
    public function getUrlAttribute()
    {
        if (! $this->attributes['url']) return null;

        return $this->getStaticUrl($this->attributes['url']);
    }

    /**
     * @param $preview_img
     */
    public function setPreviewImgAttribute($preview_img)
    {
        if (is_file($preview_img)) {
            $this->attributes['preview_img'] = $this->uploadPostFile($preview_img , $this->img_bos_key_prefix);
        }
    }

    /**
     * @return mixed|null
     */
    public function getPreviewImgAttribute()
    {
        if (! $this->attributes['preview_img']) return null;

        return $this->getStaticUrl($this->attributes['preview_img']);
    }

    /**
     *  注册删除bosKey事件绑定
     *
     */
    protected static function boot()
    {
        parent::boot();

        /*
         * 监听bos清理事件
         */
        self::observe(BosCleanObserver::class);
    }
}
